package com.seqb.common.dialect;

import com.seqb.manage.file.domain.FileDO;
import com.seqb.manage.file.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.WebEngineContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressionParser;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/15
 */
public class UploadFilesProcessor extends AbstractElementTagProcessor {

    private static final int PRECEDENCE = 1000;

    public UploadFilesProcessor(final String dialectPrefix, final String tagName) {
        super(TemplateMode.HTML, dialectPrefix, tagName, true, null, false, PRECEDENCE);
    }

    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag tag, IElementTagStructureHandler structureHandler) {
        /**
         * 获取应用程序的上下文参数
         */
        WebEngineContext webEngineContext = (WebEngineContext) context;
        final String ctx = webEngineContext.getServletContext().getContextPath();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(webEngineContext.getServletContext());

        /**
         * 获取标签各属性
         */
        Long domainId = null;
        String domainFileIds = null;
        //获得Thymeleaf标准表达式解析器
        final IStandardExpressionParser parser = new StandardExpressionParser();
        if (StringUtils.isNotEmpty(tag.getAttributeValue("domainId"))) {
            //将属性值解析为Thymeleaf标准表达式
            final IStandardExpression evaluableExpression = parser.parseExpression(context, tag.getAttributeValue("domainId"));
            //执行表达工式，获取domainId的值
            domainId = (Long) evaluableExpression.execute(context);
        }
        if (StringUtils.isNotEmpty(tag.getAttributeValue("domainFileIds"))) {
            //将属性值解析为Thymeleaf标准表达式
            final IStandardExpression evaluableExpression = parser.parseExpression(context, tag.getAttributeValue("domainFileIds"));
            //执行表达工式，获取domainId的值
            domainFileIds = (String) evaluableExpression.execute(context);
        }
        String domainName = tag.getAttributeValue("domainName");  //获取标签domainName属性
        String domainField = tag.getAttributeValue("domainField");  //获取标签domainField属性
        String domainUpdate = tag.getAttributeValue("domainUpdate");  //获取标签domainUpdate属性

        String isView = "";  //获取标签domainField属性
        if (StringUtils.isNotEmpty(tag.getAttributeValue("isView"))) {
            isView = tag.getAttributeValue("isView");
        }
        List<FileDO> fileList = null;
        if (domainId != null) {
            FileService fileService = ac.getBean(FileService.class);
            Map params = new HashMap(16);
            params.put("domainId", domainId);
            params.put("domainName", domainName);
            params.put("domainField", domainField);
            fileList = fileService.list(params);
        }
        if (!StringUtils.isEmpty(domainFileIds)) {
            FileService fileService = ac.getBean(FileService.class);
            fileList = fileService.listByIds(domainFileIds);
        }
        if (!StringUtils.isEmpty(domainUpdate)) {
            if ("false".equals(domainUpdate)) {
                domainId = null;
            }
        }
        StringBuffer html = new StringBuffer();
        html.append("<div class=\"thumbnail\">\r\n");
        html.append("   <div class=\"layui-upload-list\">\r\n");
        html.append("       <table class=\"layui-table\">\r\n");
        html.append("           <thead>\r\n");
        html.append("               <tr>\r\n");
        html.append("                   <th>文件名</th>\r\n");
        html.append("                   <th>大小</th>\r\n");
        html.append("                   <th>状态</th>\r\n");
        html.append("                   <th>操作</th>\r\n");
        html.append("               </tr>\r\n");
        html.append("           </thead>\r\n");
        html.append("           <tbody id=\"").append(domainField).append("_list\">\r\n");
        if (fileList != null && fileList.size() > 0) {
            for (FileDO file : fileList) {
                html.append("<tr id=\"upload-files-").append(file.getId()).append("\">\r\n");
                html.append("<td>").append(file.getFileName()).append("</td>\r\n");
                html.append("<td>").append(file.getFileSize() / 1000).append("kb</td>\r\n");
                html.append("<td><span style=\"color: #5FB878;\">已上传</span></td>\r\n");
                html.append("<td>");
                if (!"true".equals(isView)) {
                    html.append("<input type=\"button\" value=\"删除\" class=\"layui-btn layui-btn-mini layui-btn-danger\" onclick=\"deleteFileForUpload('").append(file.getId()).append("','").append(file.getFileUrl()).append("')\">\r\n");
                }
                html.append("<input type=\"button\" value=\"下载\" class=\"layui-btn layui-btn-mini layui-btn-normal\" onclick=\"downloadFileForUpload('").append(file.getId()).append("','").append(file.getFileUrl()).append("')\"></td>\r\n");
                html.append("</tr>\r\n");
            }
        }
        html.append("           </tbody>\r\n");
        html.append("       </table>\r\n");
        html.append("   </div>\r\n");
        if (!"true".equals(isView)) {
            html.append("   <button type=\"button\" class=\"layui-btn layui-btn-normal\" id=\"").append(domainField).append("_button\"><i class=\"layui-icon\">\uE654</i>选择文件</button>\r\n");
        }

        html.append("   <input id=\"").append(domainField).append("_fileIds\" name=\"").append(domainField).append("FileIds\" class=\"form-control\" type=\"hidden\">\r\n");
        html.append("</div>\r\n");
        html.append("<script type=\"text/javascript\">\r\n");
        html.append("   layui.use(\"upload\", function () {\r\n");
        html.append("       var upload = layui.upload;\r\n");
        html.append("       var uploadListIns = upload.render({\r\n");
        html.append("           elem: \"#").append(domainField).append("_button\",\r\n");
        html.append("           url: ctx+\"/manage/file/file/upload\", //上传接口\r\n");
        html.append("           data: {domainId : \"").append(domainId == null ? "" : domainId).append("\",domainName : \"").append(domainName).append("\",domainField : \"").append(domainField).append("\"},\r\n");
        html.append("           accept: \"file\",\r\n");
        html.append("           multiple: true,\r\n");
        html.append("           done: function(res, index, upload){\r\n");
        html.append("               if(res.code == 0){ //上传成功\r\n");
        html.append("                   var tr = $([\"<tr id='upload-files-\"+ res.fileId +\"'>\",\r\n");
        html.append("                   \"<td>\"+ res.fileName +\"</td>\",\r\n");
        html.append("                   \"<td>\"+ (res.fileSize/1014).toFixed(1) +\"kb</td>\",\r\n");
        html.append("                   \"<td>已上传</td>\",\r\n");
        html.append("                   \"<td><input type='button' value='删除' class='layui-btn layui-btn-mini layui-btn-danger upload-files-delete'><input type='button' value='下载' class='layui-btn layui-btn-mini layui-btn-normal upload-files-download'></td>\",\r\n");
        html.append("                   \"</tr>\"].join(\"\"));\r\n");
        html.append("                   \r\n");
        html.append("                   tr.find(\".upload-files-delete\").on(\"click\", function(){deleteFileForUpload(res.fileId,res.fileUrl)});   //删除\r\n");
        html.append("                   tr.find(\".upload-files-download\").on(\"click\", function(){downloadFileForUpload(res.fileId,res.fileUrl,res.fileName)});   //下载\r\n");
        html.append("                   $(\"#").append(domainField).append("_list\").append(tr);\r\n");
        html.append("                   fillIdForUpload(\"").append(domainField).append("_fileIds\",res.fileId); //上传成功后填充文件id到**_fileIds元素中\r\n");
        html.append("               }\r\n");
        html.append("               else{\r\n");
        html.append("                   layer.msg(res.msg);\r\n");
        html.append("               }\r\n");
        html.append("           }\r\n");
        html.append("       });\r\n");
        html.append("   });\r\n");
        html.append("</script>\r\n");

        /**
         * 创建DOM元素模型，修改tag标签的内容
         */
        final IModelFactory modelFactory = context.getModelFactory();
        final IModel model = modelFactory.createModel();
        model.add(modelFactory.createText(html.toString()));
        structureHandler.replaceWith(model, false);
    }

}
